package com.guodi.map.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guodi.common.constant.StatusCode;
import com.guodi.common.utils.HttpRequester;
import com.guodi.common.utils.PageData;
import com.guodi.common.utils.ReadFileUtil;
import com.guodi.common.utils.UuidUtil;
import com.guodi.core.boot.ctrl.BaseController;
import com.guodi.core.tool.api.R;
import com.guodi.map.config.HideLayerServiceConfig;
import com.guodi.map.constant.MapConst;
import com.guodi.map.constant.ZTreeIconSkin;
import com.guodi.map.entity.MapDataSource;
import com.guodi.map.service.IMapDataSourceService;
import com.guodi.map.utils.VerificationUtil;
import com.guodi.map.vo.ApiMapDataSource;
import com.guodi.map.vo.ZTreeNodeVO;
import com.guodi.system.feign.ISysClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;


/**
 * @描述：地图数据源表控制类
 * @作者: 代鹏刚
 * @日期: 2019-12-20
 */
@Validated
@RestController
@RequestMapping("/MapDataSource")
@Api(value = "API - MapDataSourceController", tags = "地图数据源表")
public class MapDataSourceController extends BaseController {

    @Autowired
    public IMapDataSourceService mapDataSourceService;

    @Resource
    public ISysClient iSysClient;

    @Autowired
    private HideLayerServiceConfig hideLayers;

    private final String mapServer="MapServer";

    /**
     * @描述: 根据实体属性分页查询
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-20
     **/
    @PostMapping("/listByEntity")
    @ApiOperation(value = " 根据实体属性分页查询")
    public R listByEntity(Page page, MapDataSource mapDataSource){
        LambdaQueryWrapper<MapDataSource> wrapper = new QueryWrapper().lambda();
        if(StringUtils.isNotBlank(mapDataSource.getName())){
            wrapper.eq(MapDataSource::getName,mapDataSource.getName());
        }
        IPage<MapDataSource> iPage = mapDataSourceService.page(page, wrapper);
        return R.data(iPage);
    }

    /**
     * @描述: 根据主键查询
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-20
     **/
    @PostMapping("/findById")
    @ApiOperation(value = "根据主键查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    public R findById(String id) {
        if(StringUtils.isBlank(id)){
            return R.fail(StatusCode.ERROR_CODE_40005,"id不能为空");
        }
        MapDataSource mapDataSource = mapDataSourceService.getById(id);
        if(null != mapDataSource.getOrgId()){
            mapDataSource.setOrgName(iSysClient.getOrgName(mapDataSource.getOrgId()).getData());
        }
        return R.data(mapDataSource);
    }

    /**
     * @描述: 新增
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-20
     **/
    @PostMapping("/save")
    @ApiOperation(value = "新增")
    public R save(@Valid ApiMapDataSource apiMapDataSource){
        MapDataSource mapDataSource = new MapDataSource();
        BeanUtils.copyProperties(apiMapDataSource,mapDataSource);
        // 因为ApiMapDataSource的orgId和MapDataSource的orgId类型不同，无法自动赋值，必须手动赋值
        mapDataSource.setOrgId(Long.parseLong(apiMapDataSource.getOrgId()));
        if(!prepareData(mapDataSource, true)){
            return R.fail(StatusCode.ERROR_CODE_40005,"该资源名称已经存在，请更换！");
        }
        mapDataSource.setId(UuidUtil.get32UUID());
        mapDataSourceService.save(mapDataSource);
        return R.data(mapDataSource);
    }

    /**
     * @描述: 修改
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-20
     **/
    @PostMapping("/update")
    @ApiOperation(value = "修改")
    public R update(MapDataSource mapDataSource) {
        if(!prepareData(mapDataSource, false)){
            return R.fail(StatusCode.ERROR_CODE_40005,"该资源名称已经存在，请更换！");
        }
        mapDataSourceService.updateById(mapDataSource);
        return R.data(mapDataSource);
    }

    /**
     * @描述: 根据主键删除
     * @入参: id
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019-12-20
     **/
    @PostMapping("/delete")
    @ApiOperation(value = "根据主键删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true,
                    dataType = "string", paramType = "query")
    })
    public R delete(String id){
        mapDataSourceService.removeById(id);
        return R.status(true);
    }

    /**
     * @描述:获取数据源树数据集
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019/12/23 10:17
     **/
    @PostMapping("/listTree")
    @ApiOperation(value = "获取数据源树数据集")
    public R listTree() {
        // 存储数据源树数据集
        List<ZTreeNodeVO> treeList = new ArrayList<ZTreeNodeVO>();
        // 查询全部数据源集合
        List<MapDataSource> list = mapDataSourceService.list();
        for(MapDataSource mapDataSource : list){
            ZTreeNodeVO dsZTreeNode = new ZTreeNodeVO();
            dsZTreeNode.setId(mapDataSource.getId());
            dsZTreeNode.setName(mapDataSource.getName());
            dsZTreeNode.setPId("-1");
            dsZTreeNode.setIconSkin(ZTreeIconSkin.ICON_SKIN_DATASOURCE);
            dsZTreeNode.setOpen(true);
            dsZTreeNode.setOrgId(mapDataSource.getOrgId());
            PageData dataPd = new PageData();
            dataPd.put("softwareType",mapDataSource.getSoftwareType());
            dataPd.put("sourceUrl",mapDataSource.getSourceUrl());
            dsZTreeNode.setPd(dataPd);
            treeList.add(dsZTreeNode);
        }
        return R.data(treeList);
    }

    /**
     * @描述:加载数据源ztree树节点数据集
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019/12/23 11:30
     **/
    @PostMapping("/loadServerTree")
    @ApiOperation(value = "加载数据源ztree树节点数据集")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "sourceId", value = "数据源Id", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "parentId", value = "当前选中ID", required = true, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "serverUrl", value = "服务URL", dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "softwareType", value = "软件类型", required = true, dataType = "string", paramType = "query")
    })
    public R loadServerTree(String sourceId, String parentId, String serverUrl, String softwareType) {
        List<ZTreeNodeVO> treeList = new ArrayList<>();
        if(softwareType.equals(MapConst.MAP_SERVICE_TYPE_ARCGIS)) {
            // arcgis服务
            treeList = this.getChildrenTreeByArcgis(sourceId, parentId, serverUrl);
        } else if (softwareType.equals(MapConst.MAP_SERVICE_TYPE_PLATFORM)) {
            // 基础信息平台(吉奥)
            treeList = this.getChildrenTreeByPlatform(serverUrl, parentId);
        } else if(softwareType.equalsIgnoreCase(MapConst.MAP_SERVICE_TYPE_BASIS_PLATFORM)){
            // 国土空间基础信息平台
            treeList = this.getChildrenTreeByBasisPlatform(sourceId, parentId, serverUrl);
        } else {
            treeList = this.getChildrenTreeByIServer(sourceId, parentId, serverUrl);
        }
        return R.data(treeList);
    }




    /**
     * @描述：根据国土空间基础信息平台获取地图服务图层集合
     * @作者：陈宏成
     * @日期：2021-04-07
     **/
    public List<ZTreeNodeVO> getChildrenTreeByBasisPlatform(String sourceId, String parentId, String serverUrl){
        // 存储ztree数据集
        List<ZTreeNodeVO> treeList = new ArrayList<ZTreeNodeVO>();
        // 如果服务地址没有，那就先查数据库获取服务地址
        MapDataSource mapDataSource = mapDataSourceService.getById(sourceId);
        serverUrl = StringUtils.isNotBlank(serverUrl)? serverUrl : mapDataSource.getSourceUrl();
        // 检查服务地址是不是这种类型
        if(serverUrl.indexOf("/service-manage") == -1 || !MapConst.MAP_SERVICE_TYPE_BASIS_PLATFORM.equalsIgnoreCase(mapDataSource.getSoftwareType())){
            return treeList;
        }
        // 从url中提取参数
        Map<String,String> paramsMap = new HashMap<>();
        String originalUrl = HttpRequester.getParamFromUrl(serverUrl,paramsMap);
        // 如果parentId和sourceId一致，则说明是顶层结构，也就是数据源，如果serverUrl里面有dirId，则使用dirId。否则默认dirId为0
        if (sourceId.equals(parentId)){
            paramsMap.put("dirId",paramsMap.containsKey("dirId")? paramsMap.get("dirId") : "0");
        }else{
            // 如果parentId和sourceId不一致，则使用parentId作为dirId
            paramsMap.put("dirId",parentId);
        }
        // 如果这个是服务图层，则请求参数加上f=pjson
        if (originalUrl.indexOf("/arcgis/rest/services") != -1){
            paramsMap.put("f","pjson");
        }
        String dataJsonStr = ReadFileUtil.getStringByUrl(originalUrl, paramsMap);
        System.err.println(dataJsonStr);
        // 如果请求失败，直接返回空列表
        if (StringUtils.isBlank(dataJsonStr)){
            return treeList;
        }
        // 解析json
        JSONObject dataJson = JSONObject.fromObject(dataJsonStr);
        // 如果有data数据项，就是正常的目录和service
        if (dataJson.containsKey("data") && dataJson.getJSONObject("data") != null){
            JSONObject dataObject = dataJson.getJSONObject("data");
            if (dataObject.containsKey("childMenu") && dataObject.getJSONArray("childMenu") != null){
                for(Object object : dataObject.getJSONArray("childMenu")) {
                    JSONObject menu = (JSONObject)object;
                    ZTreeNodeVO folderZtreeNode = new ZTreeNodeVO();
                    folderZtreeNode.setId(menu.getString("id"));
                    folderZtreeNode.setName(menu.getString("text"));
                    folderZtreeNode.setPId(menu.getString("parentId"));
                    folderZtreeNode.setIconSkin(ZTreeIconSkin.ICON_SKIN_LAYER_DIR);
                    folderZtreeNode.setParent(true);
                    // 设置自定义数据集
                    PageData dataPd = new PageData();
                    dataPd.put("server_url", serverUrl);
                    dataPd.put("source_id",sourceId);
                    dataPd.put("release_type",MapConst.MAP_SERVICE_TYPE_BASIS_PLATFORM);
                    folderZtreeNode.setPd(dataPd);
                    // 节点实体添加到集合
                    treeList.add(folderZtreeNode);
                }
            }
            if (dataObject.containsKey("serviceList") && dataObject.getJSONArray("serviceList") != null){
                for(Object object : dataObject.getJSONArray("serviceList")) {
                    JSONObject service = (JSONObject)object;
                    ZTreeNodeVO folderZtreeNode = new ZTreeNodeVO();
                    folderZtreeNode.setId(service.getString("id"));
                    folderZtreeNode.setName(service.getString("serviceName"));
                    folderZtreeNode.setPId(service.getString("dirId"));
                    folderZtreeNode.setIconSkin(ZTreeIconSkin.ICON_SKIN_LAYER_DIR);
                    folderZtreeNode.setParent(true);
                    // 设置自定义数据集
                    PageData dataPd = new PageData();
                    String proxyUrl = service.getString("proxyUrl");
                    proxyUrl = HttpRequester.setParamToUrl(proxyUrl,paramsMap);
                    dataPd.put("server_url",proxyUrl );
                    dataPd.put("source_id",sourceId);
                    dataPd.put("release_type",MapConst.MAP_SERVICE_TYPE_BASIS_PLATFORM);
                    folderZtreeNode.setPd(dataPd);
                    // 节点实体添加到集合
                    treeList.add(folderZtreeNode);
                }
            }
        }else{
            // 如果没有data项，则可能是arcgis的服务返回结果，读取layers
            if(dataJson.containsKey("layers") && dataJson.getJSONArray("layers") != null){
                for(Object object : dataJson.getJSONArray("layers")) {
                    JSONObject layer = (JSONObject)object;
                    ZTreeNodeVO layerZtreeNode = new ZTreeNodeVO();
                    String tableId = layer.getString("id");
                    layerZtreeNode.setId(tableId);
                    layerZtreeNode.setName(layer.getString("name"));
                    layerZtreeNode.setPId(parentId);
                    layerZtreeNode.setIconSkin(ZTreeIconSkin.ICON_SKIN_LAYER);
                    // 设置自定义数据集
                    PageData dataPd = new PageData();
                    // 给代理url拼接数据源的参数
                    String proxyUrl = originalUrl;
                    proxyUrl = HttpRequester.setParamToUrl(proxyUrl,paramsMap);
                    dataPd.put("server_url", proxyUrl);
                    dataPd.put("layer_table", tableId);
                    dataPd.put("release_type",MapConst.MAP_SERVICE_TYPE_BASIS_PLATFORM);
                    layerZtreeNode.setPd(dataPd);
                    treeList.add(layerZtreeNode);
                }
            }
        }
        return treeList;
    }


    /**
     * @描述：根据基础信息平台(吉奥)获取地图服务图层集合
     * @作者：彭辉
     * @日期：2020/12/3 12:07
     **/
    public List<ZTreeNodeVO> getChildrenTreeByPlatform(String serverUrl, String parentId) {
        // 存储ztree数据集
        List<ZTreeNodeVO> treeList = new ArrayList<ZTreeNodeVO>();
        // 判断数据源url是否存在
        boolean isExists = ReadFileUtil.isExistHttpURLConnection(serverUrl);
        if(!isExists){
            return treeList;
        }

        // 获取服务授权代码
        String[] gtokens = serverUrl.substring(serverUrl.indexOf("?") + 1).split("=");
        // 查询参数
        Map<String, String> paramMap = new HashMap<String, String>();
        paramMap.put(gtokens[0], gtokens[1]);
        paramMap.put("f", "pjson");
        // 读取数据源url获取json数据集
        serverUrl = serverUrl.substring(0, serverUrl.indexOf("?"));
        String dataJsonStr = ReadFileUtil.getStringByUrl(serverUrl, paramMap);
        JSONObject dataJson = JSONObject.fromObject(dataJsonStr);
        // 读取layers
        if(dataJson.get("layers") != null && StringUtils.isNotBlank(dataJson.getString("layers"))){
            /*if(dataJson.get("tileInfo") != null && StringUtils.isNotBlank(dataJson.getString("tileInfo"))){
                String[] serverArray = serverUrl.split("/");
                String name = serverArray[serverArray.length - 2] + "(切片)";
                ZTreeNode layerZtreeNode = new ZTreeNode();
                layerZtreeNode.setId("layer_" + parentId + "_" + -1);
                layerZtreeNode.setName(name);
                layerZtreeNode.setpId(parentId);
                layerZtreeNode.setIconSkin(ZTreeIconSkin.ICON_SKIN_LAYER);
                // 设置自定义数据集
                PageData dataPd = new PageData();
                dataPd.put("server_url", serverUrl);
                dataPd.put("layer_table", "-1");
                dataPd.put("release_type",MapConst.MAP_SERVICE_TYPE_PLATFORM);
                dataPd.put(gtokens[0], gtokens[1]);
                layerZtreeNode.setPd(dataPd);
                treeList.add(layerZtreeNode);
            }*/
            JSONArray layers = dataJson.getJSONArray("layers");
            for(int i = 0; i < layers.size(); i++) {
                JSONObject layerJson = layers.getJSONObject(i);
                ZTreeNodeVO layerZtreeNode = new ZTreeNodeVO();
                layerZtreeNode.setId("layer_"+parentId+"_"+i);
                layerZtreeNode.setName(layerJson.getString("name"));
                layerZtreeNode.setPId(parentId);
                layerZtreeNode.setIconSkin(ZTreeIconSkin.ICON_SKIN_LAYER);
                // 设置自定义数据集
                PageData dataPd = new PageData();
                dataPd.put("server_url", serverUrl);
                dataPd.put("layer_table", layerJson.get("id").toString());
                dataPd.put("release_type",MapConst.MAP_SERVICE_TYPE_PLATFORM);
                dataPd.put(gtokens[0], gtokens[1]);
                layerZtreeNode.setPd(dataPd);
                treeList.add(layerZtreeNode);
            }
        }
        return treeList;
    }

    /**
     * @描述: 获取arcgis数据源目录树
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2019/12/23 10:18
     **/
    public List<ZTreeNodeVO> getChildrenTreeByArcgis(String sourceId, String parentId, String serverUrl) {
        // 存储ztree数据集
        List<ZTreeNodeVO> treeList = new ArrayList<ZTreeNodeVO>();
        boolean tileFlag=false;
        // 根据id查询数据源信息
        MapDataSource mapDataSource = mapDataSourceService.getById(sourceId);
        serverUrl = serverUrl == null ? mapDataSource.getSourceUrl() : serverUrl;
//        if((serverUrl.indexOf("/geoscene/rest/services") == -1 && serverUrl.indexOf("/arcgis/rest/services") == -1 &&serverUrl.indexOf("geoserver/rest/services")==-1 ) || !MapConst.MAP_SERVICE_TYPE_ARCGIS.equals(mapDataSource.getSoftwareType())){
//            return treeList;
//        }

        // 判断数据源url是否存在
        boolean isExists = ReadFileUtil.isExistHttpURLConnection(mapDataSource.getSourceUrl());
        if(!isExists){
            return treeList;
        }

        // 读取数据源url获取json数据集
        String jsonStr = ReadFileUtil.getStringByUrl(serverUrl + "?f=pjson");
        JSONObject dataJson = JSONObject.fromObject(jsonStr);
        // 读取folders
        if(dataJson.get("folders") != null && StringUtils.isNotBlank(dataJson.getString("folders"))){
            JSONArray folders = dataJson.getJSONArray("folders");
            for(int i = 0; i < folders.size(); i++){
                // 数据源节点访问URL
                String newServerUrl = mapDataSource.getSourceUrl() + "/" + folders.getString(i);

                ZTreeNodeVO folderZtreeNode = new ZTreeNodeVO();
                folderZtreeNode.setId("folder_"+parentId+"_"+i);
                folderZtreeNode.setName(folders.getString(i));
                folderZtreeNode.setPId(parentId);
                folderZtreeNode.setIconSkin(ZTreeIconSkin.ICON_SKIN_LAYER_DIR);
                folderZtreeNode.setParent(true);
                // 设置自定义数据集
                PageData dataPd = new PageData();
                dataPd.put("server_url", newServerUrl);
                dataPd.put("source_id",sourceId);
                dataPd.put("release_type",MapConst.MAP_SERVICE_TYPE_ARCGIS);
                folderZtreeNode.setPd(dataPd);
                // 节点实体添加到集合
                treeList.add(folderZtreeNode);
            }
        }
        // 读取services
        if(dataJson.get("services") != null && StringUtils.isNotBlank(dataJson.getString("services"))){
            JSONArray services = dataJson.getJSONArray("services");
            for(int i = 0; i < services.size(); i++){
                JSONObject serviceJson = services.getJSONObject(i);
                Object tileInfo = serviceJson.get("tileInfo");
                if(tileInfo!=null){
                    tileFlag=true;
                }
                // 服务类型
                String serviceType = serviceJson.getString("type");
                // 服务名称
                String serviceName = serviceJson.getString("name");
                // 数据源节点访问URL
                String newServerUrl = mapDataSource.getSourceUrl() + "/" + serviceName + "/" + serviceType;
                // 截取掉"/"前面的目录
                serviceName = serviceName.lastIndexOf("/") == -1 ? serviceName : serviceName.substring(serviceName.lastIndexOf("/")+1);
                if(StringUtils.isNotBlank(serviceType) &&(!serviceType.equalsIgnoreCase("GPServer") &&!serviceType.equalsIgnoreCase("NAServer"))){
                    ZTreeNodeVO serviceZtreeNode = new ZTreeNodeVO();
                    serviceZtreeNode.setId("service_"+parentId+"_"+i);
                    serviceZtreeNode.setName(serviceName);
                    serviceZtreeNode.setPId(parentId);
                    serviceZtreeNode.setIconSkin(ZTreeIconSkin.ICON_SKIN_SERVICE);
                    serviceZtreeNode.setParent(true);
                    // 设置自定义数据集
                    PageData dataPd = new PageData();
                    dataPd.put("server_url", newServerUrl);
                    dataPd.put("source_id",sourceId);
                    dataPd.put("release_type",MapConst.MAP_SERVICE_TYPE_ARCGIS);
                    serviceZtreeNode.setPd(dataPd);
                    // 节点实体添加到集合
                    treeList.add(serviceZtreeNode);
                }
            }
        }
        String serviceTypes = serverUrl.substring(serverUrl.lastIndexOf("/")+1);
        boolean showLayerFlag=true;
        Object tileInfo = dataJson.get("tileInfo");
        if(tileInfo!=null){
            tileFlag=true;
        }
        if((hideLayers.getServiceType()!=null&&hideLayers.getServiceType().contains(serviceTypes))){
            showLayerFlag=false;
        }
        //地图切片服务
        if(mapServer.equals(serviceTypes)&&tileFlag){
            showLayerFlag=false;
        }
        // 读取layers
        if(dataJson.get("layers") != null&& StringUtils.isNotBlank(dataJson.getString("layers")) && showLayerFlag){
            JSONArray layers = dataJson.getJSONArray("layers");
            for(int i = 0; i < layers.size(); i++) {
                JSONObject layerJson = layers.getJSONObject(i);
                ZTreeNodeVO layerZtreeNode = new ZTreeNodeVO();
                layerZtreeNode.setId("layer_"+parentId+"_"+i);
                layerZtreeNode.setName(layerJson.getString("name"));
                layerZtreeNode.setPId(parentId);
                layerZtreeNode.setIconSkin(ZTreeIconSkin.ICON_SKIN_LAYER);
                // 设置自定义数据集
                PageData dataPd = new PageData();
                dataPd.put("server_url", serverUrl);
                dataPd.put("layer_table", layerJson.get("id").toString());
                dataPd.put("release_type",MapConst.MAP_SERVICE_TYPE_ARCGIS);
                layerZtreeNode.setPd(dataPd);
                treeList.add(layerZtreeNode);
            }
        }
        return treeList;
    }

    /**
     * @描述: 获取超图数据源目录树
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020/4/9 14:57
     **/
    public List<ZTreeNodeVO> getChildrenTreeByIServer(String sourceId, String parentId, String serverUrl) {
        // 存储ztree数据集
        List<ZTreeNodeVO> treeList = new ArrayList<ZTreeNodeVO>();
        // 根据id查询数据源信息
        MapDataSource mapDataSource = mapDataSourceService.getById(sourceId);
        serverUrl = serverUrl == null ? mapDataSource.getSourceUrl() : serverUrl;
        if(serverUrl.indexOf("/iserver/services") == -1 || !"iserver".equals(mapDataSource.getSoftwareType())){
            return treeList;
        }
        // 判断数据源url是否存在
        boolean isExists = ReadFileUtil.isExistHttpURLConnection(mapDataSource.getSourceUrl());
        if(!isExists){
            return treeList;
        }
        /*//判断返回类型是JSONObject还是JSONArray
        Object object = new JSONTokener(jsonStr).nextValue();*/
        //解析rest
        if(serverUrl.endsWith("rest")){
            getAnalysisData(treeList,serverUrl + "/maps.json",parentId,sourceId,"path");
            return treeList;
        }
        //解析restjsr
        if(serverUrl.endsWith("restjsr")){
            getAnalysisData(treeList,serverUrl + "/v1/vectortile.json",parentId,sourceId,"path");
            return treeList;
        }
        //解析wms
        if(serverUrl.indexOf("wms") != -1){
            getAnalysisData(treeList,serverUrl + ".json",parentId,sourceId,"url");
            return treeList;
        }
        //解析wmts
        if(serverUrl.indexOf("wmts") != -1){
            ZTreeNodeVO folderZtreeNode = new ZTreeNodeVO();
            folderZtreeNode.setId("layer_"+parentId+"_"+"0");
            folderZtreeNode.setName(serverUrl.substring(serverUrl.lastIndexOf("/")+1,serverUrl.length()));
            folderZtreeNode.setPId(parentId);
            folderZtreeNode.setIconSkin(ZTreeIconSkin.ICON_SKIN_LAYER);
            folderZtreeNode.setParent(true);
            // 设置自定义数据集
            PageData dataPd = new PageData();
            dataPd.put("server_url", serverUrl);
            dataPd.put("layer_table","0");
            dataPd.put("release_type","iserver");
            folderZtreeNode.setPd(dataPd);
            // 节点实体添加到集合
            treeList.add(folderZtreeNode);
            return treeList;
        }
        // 读取数据源url获取json数据集
        String jsonStr = ReadFileUtil.getJsonByUrl(serverUrl + ".json");
        //解析目录
        JSONArray jsonArray = JSONArray.fromObject(jsonStr);
        for(int i = 0; i < jsonArray.size(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            //筛选地图服务数据
            if(jsonObject.getString("componentType").endsWith("MapImpl")){
                ZTreeNodeVO folderZtreeNode = new ZTreeNodeVO();
                folderZtreeNode.setId("layer_"+parentId+"_"+i);
                folderZtreeNode.setName(jsonObject.getString("name"));
                folderZtreeNode.setPId(parentId);
                folderZtreeNode.setIconSkin(ZTreeIconSkin.ICON_SKIN_LAYER_DIR);
                folderZtreeNode.setParent(true);
                // 设置自定义数据集
                PageData dataPd = new PageData();
                dataPd.put("server_url", jsonObject.getString("url"));
                dataPd.put("source_id",sourceId);
                dataPd.put("release_type","iserver");
                folderZtreeNode.setPd(dataPd);
                // 节点实体添加到集合
                treeList.add(folderZtreeNode);
            }
        }
        return treeList;
    }

    /**
     * @描述: 解析图层或者目录
     * @入参:
     * @出参:
     * @作者: 代鹏刚
     * @日期: 2020/4/10 8:57
     **/
    public List<ZTreeNodeVO> getAnalysisData(List<ZTreeNodeVO> treeList, String serverUrl, String parentId, String sourceId, String type){
        String jsonStr = ReadFileUtil.getJsonByUrl(serverUrl);
        //解析图层
        JSONArray jsonArray = JSONArray.fromObject(jsonStr);
        for(int i = 0; i < jsonArray.size(); i++){
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            ZTreeNodeVO folderZtreeNode = new ZTreeNodeVO();
            folderZtreeNode.setId("layer_"+parentId+"_"+i);
            if(type.equals("url")){
                folderZtreeNode.setName(serverUrl.substring(serverUrl.lastIndexOf("/")+1,serverUrl.length()-5));
            }else {
                folderZtreeNode.setName(jsonObject.getString("name"));
            }
            folderZtreeNode.setPId(parentId);
            folderZtreeNode.setIconSkin(ZTreeIconSkin.ICON_SKIN_LAYER);
            // 设置自定义数据集
            PageData dataPd = new PageData();
            dataPd.put("server_url", jsonObject.getString(type));
            dataPd.put("layer_table",i);
            dataPd.put("release_type","iserver");
            folderZtreeNode.setPd(dataPd);
            // 节点实体添加到集合
            treeList.add(folderZtreeNode);
        }
        return  treeList;
    }


    private boolean prepareData(MapDataSource mapDataSource, boolean isSave) {
        //判断当前目录下，目录名称是否已经存在
        List<MapDataSource> list = (List<MapDataSource>)mapDataSourceService.listByMap(VerificationUtil.verifyMap(mapDataSource.getName(),null));
        if(isSave){
            if(list.size() > 0){
                return false;
            }
            mapDataSource.setCreator(getUser().getUserId());
            mapDataSource.setCreateTime(new Date());
            //防止误修改
            mapDataSource.setModifier(null);
            mapDataSource.setModifyTime(null);
            return true;
        }else{
            if(list.size() > 0 && !list.get(0).getId().equals(mapDataSource.getId())){
                return false;
            }
            mapDataSource.setModifier(getUser().getUserId());
            mapDataSource.setModifyTime(new Date());
            //防止误修改
            mapDataSource.setCreator(null);
            mapDataSource.setCreateTime(null);
            return true;
        }
    }
}
